
const enableGrag = (el: HTMLElement, binding, vNode) => {
  let moveEl = el as HTMLElement
  const mouseDown = (e: MouseEvent) => {
    //鼠标点击物体那一刻相对于物体左侧边框的距离=点击时的位置相对于浏览器最左边的距离-物体左边框相对于浏览器最左边的距离
    // console.log(e.clientX, e.clientY, "-----起始", el.offsetLeft);
    let X = e.clientX - el.offsetLeft;
    let Y = e.clientY - el.offsetTop;
    const maxX = binding.value?.maxX || 500;
    const maxY = binding.value?.maxY || 500;
    const minX = binding.value?.minX || 0;
    const minY = binding.value?.minY || 0;
    const cb = binding.value?.cb;
    const move = (e: MouseEvent) => {
      // 获取拖拽元素的位置
      let left = e.clientX - X;
      let top = e.clientY - Y;
      
      if (left <= minX) {
        left = minX;
      } else if (left >= maxX - el.offsetWidth) {
        left = maxX - el.offsetWidth;
      }
      
      if (top <= minY) {
        top = minY;
      } else if (top > maxY - el.offsetHeight) {
        top = maxY - el.offsetHeight;
      }

      el.style.left = left + "px";
      el.style.top = top + "px";
      cb && cb(left, top)
    };
    document.addEventListener("mousemove", move);
    document.addEventListener("mouseup", () => {
      document.removeEventListener("mousemove", move);
    });
  };
  moveEl.addEventListener("mousedown", mouseDown);
}
const drag = {
  updated(el: HTMLElement, binding, vNode) {
    enableGrag(el, binding, vNode);
  },
}

const directives = {
  install: function (app: any) {
    app.directive('drag', drag)
  }
}
export default directives
